<template>
  <div class="container">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="ruleForm"
      status-icon
    >
      <div class="form-section">
        <div class="flag"></div>
        <span class="title">基本信息</span>
        <el-divider></el-divider>
      </div>

      <el-form-item label="分组名称" prop="name">
        <el-input
          v-model.trim="ruleForm.name"
          maxlength="32"
          :disabled="is_preview"
          show-word-limit
          placeholder="请输入分组名称"
          style="width:500px;"
          clearable
        ></el-input>
      </el-form-item>

      <!-- <el-form-item label="分组备注" prop="note"> -->
      <el-form-item label="分组备注">
        <el-input
          type="textarea"
          v-model.trim="ruleForm.note"
          :disabled="is_preview"
          maxlength="255"
          show-word-limit
          placeholder="请输入分组备注"
          style="width:500px;"
        ></el-input>
      </el-form-item>

      <div class="form-section">
        <div class="flag"></div>
        <span class="title">分组规则</span>
        <el-divider></el-divider>
      </div>

      <el-form-item label="创建规则"></el-form-item>

      <div class="cus-form-item">
        <rule-config ref="ruleObj"></rule-config>
        <div v-if="!submitPass && ruleNums === 0" class="cus-form-item__error">
          请至少创建一条规则
        </div>
      </div>

      <el-form-item label="更新方式" prop="updateMode" id="updateMode">
        <span>自动更新</span>
        <span style="margin: 0 5px 0 15px;">每</span>

        <el-select
          v-model="ruleForm.upakey"
          size="mini"
          :disabled="is_preview"
          @change="handleChange"
          placeholder="请选择"
          style="width:120px; margin-right:5px;"
          filterable
          clearable
        >
          <el-option
            v-for="item in updateWayDic"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>

        <el-select
          v-model="ruleForm.upaVal"
          v-if="ruleForm.updateMode !== 'DAY'"
          size="mini"
          :disabled="is_preview"
          placeholder="请选择"
          style="width:120px;"
          filterable
          clearable
        >
          <el-option
            v-for="item in updateWayVal"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>

        <span style="margin-left:5px;"> 07点40分 </span>
      </el-form-item>

      <el-form-item label="是否启用">
        <el-radio-group v-model="ruleForm.enable" :disabled="is_preview">
          <el-radio label="open">启用</el-radio>
          <el-radio label="close">关闭</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="!is_preview" style="margin-left:100px;">
        <el-button @click="resetForm('ruleForm')" style="margin-right:100px;"
          >取消</el-button
        >
        <el-button type="success" @click="validateForm('ruleForm')"
          >确定</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import dateJson from './modules/dateJson'
import { clearTagMixins } from '@/mixins/clearTag.js'
import {
  checkGroupName,
  appendUserGroup,
  editUserGroup,
  userGroupDetails
} from '@/api/userGroup'
import ruleConfig from '@/components/userGroup/ruleCreateGroup/modules/ruleConfig'

export default {
  msg: '规则创建分组',
  data() {
    // name Validate
    const nameValidate = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请填写分组名称'))
      } else {
        if (this.pageType === 'edit') {
          if (this.ruleForm.name !== this.nameCache) {
            checkGroupName({ name: value }, (res) => {
              if (res) {
                callback(new Error('分组名称不可重复'))
              } else {
                callback()
              }
            })
          } else {
            callback()
          }
        } else {
          checkGroupName({ name: value }, (res) => {
            if (res) {
              callback(new Error('分组名称不可重复'))
            } else {
              callback()
            }
          })
        }
      }
    }

    // update mode Validate
    const updateModeValidate = (rule, value, callback) => {
      const { upakey, upaVal, updateMode } = this.ruleForm
      if (upakey === '' || (updateMode !== 'DAY' && upaVal === '')) {
        callback(new Error('请选择更新方式'))
      } else {
        callback()
      }
    }

    return {
      ruleForm: {
        name: '',
        note: '',
        upakey: '',
        upaVal: '',
        updateMode: '',
        enable: 'open'
      },

      // group name
      nameCache: '',

      // status
      submitPass: true,

      // dictionary
      updateWayDic: [
        { value: 'MONTH', label: '月' },
        { value: 'WEEK', label: '周' },
        { value: 'DAY', label: '天' }
      ],

      updateWayVal: [],

      // validate rules
      rules: {
        name: [{ required: true, validator: nameValidate, trigger: 'blur' }],
        // note: [
        //   { required: true, message: '请填写分组备注', trigger: 'blur' }
        // ],
        updateMode: [
          { required: true, validator: updateModeValidate, trigger: 'change' }
        ]
      },

      // submit form
      formData: {
        configData: {
          operate: '',
          userBehavior: {},
          userProperties: {}
        },

        autoUpdateConfig: {
          day: 0,
          frequency: ''
        },

        groupCreationType: '',
        groupStatus: true,
        name: '',
        note: '',
        serial: '',
        updateMethod: ''
      }
    }
  },

  mixins: [clearTagMixins],

  computed: {
    ...mapGetters('userGroup', {
      ruleNums: 'ruleNumsGetter',
      ruleValidate: 'ruleValidateGetter'
    }),

    pageType() {
      // edit / add / preview
      return this.$route.query.pageType
    },

    is_preview() {
      return this.pageType === 'preview' ? true : false
    }
  },

  created() {
    const query = ['preview', 'edit']
    if (query.includes(this.pageType)) {
      userGroupDetails(
        this.$route.query.id,
        (res) => {
          //edit 情况下 【记录下分组名】
          this.nameCache = res.name
          this.initForm(res)
        },
        (err) => {
          this.$message({
            message: err.message,
            type: 'warning'
          })
        }
      )
    }
  },

  methods: {
    // init Form
    initForm(data) {
      const { name, note, groupStatus, configData, autoUpdateConfig } = data

      this.ruleForm.name = name
      this.ruleForm.note = note
      this.ruleForm.enable = groupStatus ? 'open' : 'close'
      this.ruleForm.upaVal = autoUpdateConfig.day
      this.ruleForm.upakey = autoUpdateConfig.frequency
      this.ruleForm.updateMode = autoUpdateConfig.frequency
      this.updateWayVal = dateJson[autoUpdateConfig.frequency]

      this.$refs.ruleObj.$emit('initRuleForm', configData)
    },

    // validate Form
    validateForm(formName) {
      // update submit status
      this.submitPass = true

      // validate child form
      this.$refs.ruleObj.$emit('submitValidate')

      // validate parent form
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.submitPass = false
        }

        // validate rules number
        if (this.ruleNums === 0) {
          this.submitPass = false
        }

        if (this.submitPass && this.ruleValidate) {
          this.submitForm()
        }
      })
    },

    // submit data
    submitForm() {
      this.formData.name = this.ruleForm.name
      this.formData.note = this.ruleForm.note
      this.formData.updateMethod = 'AUTO'
      this.formData.groupCreationType = 'RULE'
      this.formData.autoUpdateConfig.day = this.ruleForm.upaVal
      this.formData.autoUpdateConfig.frequency = this.ruleForm.upakey
      this.formData.groupStatus = this.ruleForm.enable === 'open' ? true : false

      // 子组件数据对象 & 数据结构
      const {
        firstLevel,
        secondAttrLevel,
        secondBehaviorLevel,
        attrList,
        attrCard,
        behaviorList,
        behaviorCard
      } = this.$refs.ruleObj
      // 第一层级关系
      this.formData.configData.operate = firstLevel.active.toUpperCase()

      // 第二层用户属性 【关系 & 数据结构】
      this.formData.configData.userProperties.operate = secondAttrLevel.active.toUpperCase()
      this.formData.configData.userProperties.rule = []

      // 用户属性 单条件
      attrList.forEach((ele) => {
        let newObj = {
          operate: 'AND',
          ruleConfig: { type: 'userProperties', userProperties: {} }
        }
        newObj.ruleConfig.userProperties.index = ele.attr
        newObj.ruleConfig.userProperties.condition = ele.rule
        newObj.ruleConfig.userProperties.valueStart = String(ele.attrVal)
        newObj.ruleConfig.userProperties.valueEnd = ele.valueEnd
        if (ele.rule == 'section' && ele.element == 'Date') {
          newObj.ruleConfig.userProperties.valueStart = ele.attrVal[0]
          newObj.ruleConfig.userProperties.valueEnd = ele.attrVal[1]
        }

        this.formData.configData.userProperties.rule.push(newObj)
      })

      // 用户属性 条件组
      attrCard.forEach((ele) => {
        let newRule = {
          operate: ele.condition ? ele.condition.active.toUpperCase() : 'AND',
          rule: []
        }

        ele.child.forEach((child) => {
          let newObj = {
            ruleConfig: { type: 'userProperties', userProperties: {} }
          }
          newObj.ruleConfig.userProperties.index = child.attr
          newObj.ruleConfig.userProperties.condition = child.rule
          newObj.ruleConfig.userProperties.valueStart = String(child.attrVal)
          newObj.ruleConfig.userProperties.valueEnd = child.valueEnd
          if (child.rule == 'section' && child.element == 'Date') {
            newObj.ruleConfig.userProperties.valueStart = child.attrVal[0]
            newObj.ruleConfig.userProperties.valueEnd = child.attrVal[1]
          }
          newRule.rule.push(newObj)
        })

        newRule.rule.length &&
          this.formData.configData.userProperties.rule.push(newRule)
      })

      // 第二层行为属性 【关系 & 数据结构】
      this.formData.configData.userBehavior.operate = secondBehaviorLevel.active.toUpperCase()
      this.formData.configData.userBehavior.rule = []

      // 行为属性 单条件
      behaviorList.forEach((ele) => {
        let newObj = {
          operate: 'AND',
          ruleConfig: { type: 'userBehavior', userBehavior: {} }
        }
        newObj.ruleConfig.userBehavior.index = ele.behavior
        newObj.ruleConfig.userBehavior.condition = ele.rule
        newObj.ruleConfig.userBehavior.dimension = ele.dimension
        newObj.ruleConfig.userBehavior.valueStart = String(ele.actionNum)
        newObj.ruleConfig.userBehavior.valueEnd = ele.actionEndNum
        newObj.ruleConfig.userBehavior.period = null

        /*
          累计行为  统计只有总计(total)  且隐藏选择默认为总计(total)

          累计发送激活短信次数(all_msg)、累计听课节数(all_lscnt)、累计入量次数(all_flow)、注册至今登录天数(all_cnt)、累计非作业点赞量(all_sc_fzycnt)、累计作业点赞量(all_dz_zycnt)、累计非作业发布量(all_fzyfbcnt)、累计非作业评论量all_fzyplcnt)、累计关注量(all_gzcnt)、累计非作业收藏量(all_sc_fzycnt)、累计作业收藏量(all_sc_zycnt) 、App 推荐加载页数(app_load)、H5推荐加载页数(m_load)、Pc 推荐加载页数(pc_load)、召回次数(cnt)、总停留时长(all_times)、累计作业评论量(all_zyplcnt)   累计作业发布量(all_zyfbcnt) 未登录天数(keep_lost_date)  累计试听课节数
        */
        if (ele.element === 'Date' && ele.rule === 'section') {
          newObj.ruleConfig.userBehavior.valueStart = ele.actionNum[0]
          newObj.ruleConfig.userBehavior.valueEnd = ele.actionNum[1]
        }
        if (
          ele.dimensionList &&
          ele.dimensionList.length == 1 &&
          ele.dimensionList[0].value == 'total'
        ) {
          newObj.ruleConfig.userBehavior.dimension = 'total'
        }
        if (ele.isPeriod === '1') {
          newObj.ruleConfig.userBehavior.period = this.handleBehaviorTimeRange(
            ele
          )
        }
        
        this.formData.configData.userBehavior.rule.push(newObj)
      })

      // 行为属性 条件组
      behaviorCard.forEach((ele) => {
        let newRule = {
          operate: ele.condition ? ele.condition.active.toUpperCase() : 'AND',
          rule: []
        }

        ele.child.forEach((child) => {
          let newObj = {
            ruleConfig: { type: 'userBehavior', userBehavior: {} }
          }
          newObj.ruleConfig.userBehavior.index = child.behavior
          newObj.ruleConfig.userBehavior.condition = child.rule
          newObj.ruleConfig.userBehavior.dimension = child.dimension
          newObj.ruleConfig.userBehavior.valueStart = String(child.actionNum)
          newObj.ruleConfig.userBehavior.valueEnd = child.actionEndNum
          newObj.ruleConfig.userBehavior.period = null

          /*
            累计行为  统计只有总计(total)  且隐藏选择默认为总计(total)

            累计发送激活短信次数(all_msg)、累计听课节数(all_lscnt)、累计入量次数(all_flow)、注册至今登录天数(all_cnt)、累计非作业点赞量(all_sc_fzycnt)、累计作业点赞量(all_dz_zycnt)、累计非作业发布量(all_fzyfbcnt)、累计非作业评论量all_fzyplcnt)、累计关注量(all_gzcnt)、累计非作业收藏量(all_sc_fzycnt)、累计作业收藏量(all_sc_zycnt) 、App 推荐加载页数(app_load)、H5推荐加载页数(m_load)、Pc 推荐加载页数(pc_load)、召回次数(cnt)、总停留时长(all_times)、累计作业评论量(all_zyplcnt)   累计作业发布量(all_zyfbcnt) 未登录天数(keep_lost_date)  累计试听课节数
          */
          if (
            child.dimensionList &&
            child.dimensionList.length == 1 &&
            child.dimensionList[0].value == 'total'
          ) {
            newObj.ruleConfig.userBehavior.dimension = 'total'
          }
          if (child.element === 'Date' && child.rule === 'section') {
            newObj.ruleConfig.userBehavior.valueStart = child.actionNum[0]
            newObj.ruleConfig.userBehavior.valueEnd = child.actionNum[1]
          }
          if (child.isPeriod === '1') {
            newObj.ruleConfig.userBehavior.period = this.handleBehaviorTimeRange(
              child
            )
          }

          newRule.rule.push(newObj)
        })

        newRule.rule.length &&
          this.formData.configData.userBehavior.rule.push(newRule)
      })
      // 新增
      this.pageType === 'add' &&
        appendUserGroup(
          this.formData,
          (res) => {
            this.clearTag()
          },
          (err) => {
            this.$message({
              message: err.message,
              type: 'warning'
            })
          }
        )

      // 编辑
      this.pageType === 'edit' &&
        editUserGroup(
          this.$route.query.id,
          this.formData,
          (res) => {
            this.clearTag()
          },
          (err) => {
            this.$message({
              message: err.message,
              type: 'warning'
            })
          }
        )
    },

    // reset and return last page
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.clearTag()
    },

    // handle updateWay change
    handleChange(val) {
      this.ruleForm.upaVal = ''
      this.ruleForm.updateMode = val
      this.updateWayVal = dateJson[val]
    },

    // handle behavior time range
    handleBehaviorTimeRange(res) {
      const { timeKey, startTime, endTime } = res

      const startDate = new Date(startTime)

      const endDate = new Date(endTime)

      const timeList = {
        past: {
          type: 'DYNAMIC',
          periodRule: 'YESTERDAY',
          startDay: 1,
          endDay: 0
        },
        thisWeek: { type: 'DYNAMIC', periodRule: 'THIS_WEEK' },
        thisMonth: { type: 'DYNAMIC', periodRule: 'THIS_MONTH' },
        lastWeek: { type: 'DYNAMIC', periodRule: 'LAST_WEEK' },
        lastMonth: { type: 'DYNAMIC', periodRule: 'LAST_MONTH' },
        past_7: {
          type: 'DYNAMIC',
          periodRule: 'NEARLY_SEVEN_DAYS',
          startDay: 7,
          endDay: 0
        },
        past_30: {
          type: 'DYNAMIC',
          periodRule: 'NEARLY_THIRTY_DAYS',
          startDay: 30,
          endDay: 0
        },
        past_90: {
          type: 'DYNAMIC',
          periodRule: 'NEARLY_NINETY_DAYS',
          startDay: 90,
          endDay: 0
        },
        static_time: {
          type: 'STATIC',
          periodRule: 'STATIC',
          startTime: startDate.getTime(),
          endTime: endDate.getTime()
        },
        dynamic_time: {
          type: 'DYNAMIC',
          periodRule: 'FIXED_START_TIME',
          startTime: startDate.getTime(),
          endDay: endTime
        }
      }

      return timeList[timeKey]
    },

    // close tag
    signOut() {
      this.$router.go(-1)
    }
  },

  components: {
    ruleConfig
  }
}
</script>

<style lang="less" scoped>
@import './style.less';
</style>
